< previous page page_213 next page >

Page 213
note.gif If you are working on code that was developed by someone else, you might find a loop that starts with a While statement and ends with a Wend statement (Wend stands for "While-End," or the End of the While loop). This type of loop, left over from earlier versions of BASIC, works the same as a Do While loop with the While clause in the Do statement. Visual Basic still supports a While . . . Wend loop, but I recommend that you use the Do While type of loop because it is more flexible.  square.gif

Using a Do Until Statement
The Do Until loop is basically the same as the Do While loop except that the statements inside a Do Until loop are run only as long as the condition is False. When the condition becomes True, the loop terminates. As with the Do While loop, the Do Until loop has two forms: one with the condition in the Do statement and one with the condition in the Loop statement. If you place the condition in the Do statement, it is evaluated before the statements in the loop are executed. If you place the condition in the Loop statement, the loop is run at least once before the condition is evaluated.
A frequent use of the Do Until statement is in reading and processing data files. A loop starts with the first record of the file and processes each record until the end of file is reached. The following lines of code use a Do Until loop to load all the authors from the sample database BIBLIO.MDB into a list box:
    Dim dbTest As Database
    Dim rsTest As Recordset
    Set dbTest = OpenDatabase("biblio.mdb")
    Set rsTest = dbTest.OpenRecordset("authors")
    Do Until rsTest.EOF
        List1.AddItem rsTest("author")
        rsTest.MoveNext
    Loop
The loop does not execute at all if the condition rsTest.EOF (which signifies that the recordset is at its end) is True before the loop begins; this is an advantage of testing the condition at the beginning of the loop.
tip.gif
Indenting your code inside a loop or other structure (such as an If/Then/Else block or Select Case/End Select block) makes the code easier to read. To indent a line of code, press Tab at the beginning of the line. When you press Enter at the end of the line, the indention remains at the same point. Try to match up beginning and ending points of code blocks, as has been done in many of this book's code examples.

As with the Do While loop, the Do Until loop can be written so that it always executes at least once. Consider the following example:
    Dim I As Integer
    I = 0
    
    Do
        I = InputBox("Enter 0 to exit the loop!")
    Loop Until I = 0

 
< previous page page_213 next page >